package com.rabbiter.market.quartzjob;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.rabbiter.market.common.util.TimeUtil;
import com.rabbiter.market.domain.sale.sale_records.SaleRecords;
import com.rabbiter.market.service.pay.PayService;
import com.rabbiter.market.service.sale_management.sale_records.ISaleRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author: longxianghang
 * @date: 2025/4/19 13:04
 * @description: 订单相关定时任务
 */
@Component
public class OrderJob {

    private static final Logger logger = LoggerFactory.getLogger(OrderJob.class);

    @Resource
    private ISaleRecordsService saleRecordsService;

    @Resource
    private PayService payService;

    /**
     * 订单过期时间
     */
    @Value("${alipay.timeout-express}")
    private String timeoutExpress;

    /**
     * 关闭订单定时任务，每20秒执行一次
     */
    @Scheduled(cron = "*/20 * * * * *")
    public void orderClose() {
        logger.info("订单关闭定时任务开始执行...");

        // 全量查询所有订单
        List<SaleRecords> saleRecordsList = saleRecordsService.getAllOrder();
        if (Objects.isNull(saleRecordsList) || saleRecordsList.isEmpty()) {
            return;
        }

        List<SaleRecords> updateListOne = new ArrayList<>(); // 支付成功，但回调失败的订单
        List<SaleRecords> updateListTwo = new ArrayList<>(); // 未支付，超时需要关闭的订单
        for (SaleRecords saleRecords : saleRecordsList) {
            //获取状态
            //判断未支付 , 关闭订单
            long timeout = saleRecords.getSellTime().getTime() + TimeUtil.convertToMilliseconds(timeoutExpress);
            if(saleRecords.getPayStatus() == 10 && System.currentTimeMillis() >= timeout){
                try {
                    // 防止出现支付宝回调失败的情况
                    AlipayTradeQueryResponse response = payService.queryOrder(saleRecords.getCn(), null, null, null);
                    if (!ObjectUtils.isEmpty(response)) {
                        if ("10000".equals(response.getCode())) {
                            saleRecords.setPayStatus(20);
                            updateListOne.add(saleRecords);
                        }
                    } else {
                        saleRecords.setPayStatus(30);
                        updateListTwo.add(saleRecords);
                        // TODO 库存返还
                    }
                } catch (Exception e) {
                    saleRecords.setPayStatus(30);
                    updateListTwo.add(saleRecords);
                    logger.info("定时任务更新订单异常：", e);
                }
            }
        }

        if(!updateListOne.isEmpty()) {
            saleRecordsService.updateBatch(updateListOne, 20);
        }

        if(!updateListTwo.isEmpty()) {
            saleRecordsService.updateBatch(updateListTwo, 30);
        }

        logger.info("订单关闭定时任务执行完毕...");
    }
}
